package org.ruwang.chinamobileai.services.impl;

import lombok.RequiredArgsConstructor;
import org.ruwang.chinamobileai.services.ChatService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {

    private final VectorStore vectorStore;

    private final ChatClient chatClient;
    @Override
    public Flux<String> chatStream(String question, String sessionId) {
        //创建搜索请求,用于搜索相关文档
        SearchRequest searchRequest = SearchRequest.builder()
                .query(question)//设置查询条件
                .topK(3)//设置最多返回的文档数量
                .build();
        //调用聊天客户端生成流式响应内容

        return chatClient.prompt()
                .system(prompt->prompt.param("now",System.currentTimeMillis())) //设置系统角色参数
                .advisors(a->a.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY,sessionId))
                .advisors(b->b.advisors(new QuestionAnswerAdvisor(vectorStore,searchRequest)))
                .user(question)
                .stream()
                .content();
    }
}
